<?php defined('SYSPATH') or die('No direct script access.');
  
class Controller_Cms_Banners extends Controller_Cms_Setbackend
{
	private $model;
	
	public function before()
	{
		parent::before();
		$this->model = new Model_Cms_Banners;
    }
    
	public function action_bannerlist()
	{
		$this->template->breadcrumb = html::anchor('admin','Start')." > Banery";
		$view = View::factory('cms/banner_list');
		$view->banners = $this->model->get_banners();
		$this->template->content = $view;
	}
	
	public function action_banneredit($id)
	{
		if($_POST)
		{
			//echo Kohana::debug($_POST);exit;
			$file = $_POST['picture'];
			$url = trim($_POST['url']);
			$this->model->save_banner($id,$file,$url);
			Session::instance()->set('flash_panel','<div class="flash-ok">Banner został zmieniony</div>');
			Request::instance()->redirect('admin/banneredit/'.$id);
		}
		
		$this->template->breadcrumb = html::anchor('admin','Start')." > " . html::anchor('admin/banners','Lista banerów')." > " . " Edycja banera";
		$baner = $this->model->get_banner($id);
		$view = View::factory('cms/banner_edit');
		$folder = $_SERVER['DOCUMENT_ROOT'].Kohana::$base_url."/upload/banery/".$baner['folder']."/";
		$folder = str_replace('//','/',$folder);
		//echo $folder;exit;
		//$files = Helpers::getDirectoryList($folder);
		//echo Kohana::debug($files);exit;
		$view->units = $this->model->get_units($id);
		$view->banner = $baner;
		$this->template->content = $view;
	}
	
	public function action_delbanner($id)
	{
		$unit = $this->model->get_unit($id);
		$banner = $this->model->get_banner($unit['banner_id']);
		$folder = $_SERVER['DOCUMENT_ROOT'].Kohana::$base_url."/upload/banery/".$banner['folder']."/";
		$plik = $folder.$unit['name'];
		$plik = str_replace("//","/",$plik);
		if(file_exists($plik))
			unlink($plik);
		DB::delete('banner_units')->where('id','=',$id)->execute();
		Session::instance()->set('flash_panel','<div class="flash-ok">Plik banera został usunięty</div>');
		Request::instance()->redirect('admin/banneredit/'.$unit['banner_id']);
	}
	
	public function action_bannerorder()
	{
		if (Request::$is_ajax)
		{
			$this->auto_render=false;
			$order = $_GET['order'];
			$string = explode("-",$order);
			$new = 1;
			foreach($string as $s)
			{
				$a = substr($s,5);
				DB::update('banner_units')
					->set(array('order'=>$new))
					->where('id','=',$a)->execute();
				$new++;
			}
		}
	}
	
	public function action_changerotation()
	{
		if (Request::$is_ajax)
		{
			$this->auto_render=false;
			$banner_id = $_GET['banner_id'];
			$val = $_GET['val'];
			DB::update('banners')
				->set(array('rotation'=>$val))
				->where('id','=',$banner_id)->execute();
		}
	}
	
	public function action_changebannerurl()
	{
		if (Request::$is_ajax)
		{
			$this->auto_render=false;
			$this->model->change_url($_GET['id'],$_GET['url']);
		}
	}
}
?>